package com.liang.gridlayoutdemo

import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.os.Bundle
import android.support.constraint.ConstraintLayout
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.item_image.view.*
import kotlin.math.log
import kotlin.math.roundToInt

class MainActivity : AppCompatActivity() {
    private val column = 3;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val images = listOf(
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher_round,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher_round
        )



        recycleview_images.apply {
            layoutManager = GridLayoutManager(context, column, RecyclerView.VERTICAL, false) as RecyclerView.LayoutManager?
            addItemDecoration(EvenItemDecoration(dp2px(context, 5), column))
            adapter = ImageAdapter(images, column)
        }
    }

    override fun onBackPressed() {
        val layoutParams = text.layoutParams as ConstraintLayout.LayoutParams
        Log.e("----->","${text.bottom}    ${layoutParams.bottomMargin}");
    }

    class ImageAdapter(private val images: List<Int> = listOf(), private val column: Int) :
        RecyclerView.Adapter<ImageAdapter.ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view =
                LayoutInflater.from(parent.context).inflate(R.layout.item_image, parent, false)
            // 动态设置图片大小 保证宽高相等
            val ivSize = (getScreenContentWidth(parent.context) - dp2px(
                parent.context,
                10
            ) * (column + 1)) / column
            /**
             * 这里不用设置width的原因是，当item 设置match_parent的时候，recyclerView会自动平均分配每个item
             */
//            view.iv_image.layoutParams.width = 1000
            view.iv_image.layoutParams.height = ivSize
            return ViewHolder(view)
        }


        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.view.iv_image.setImageResource(images[position])
        }

        override fun getItemCount(): Int {
            return images.size
        }

        class ViewHolder(val view: View) : RecyclerView.ViewHolder(view)
    }


    companion object {
        fun dp2px(context: Context, dps: Int): Int {
            return (dps.toFloat() * getDensityDpiScale(context)).roundToInt()
        }

        private fun getDensityDpiScale(context: Context): Float {
            //densityDpi：屏幕密度，每英寸的像素数
            //density：密度比值，和densityDpi相关，其实就是densityDpi/160得出来的值（160密度就是谷歌定的一个密度标准）
            //scaledDensity:同density，用于文字缩放的计算，也就是sp
            //xDpi：水平方向的真实密度
//            yDpi：垂直方向的真是密度
            return context.resources.displayMetrics.xdpi / 160.0f
        }

        fun getScreenContentWidth(context: Context): Int {
            val displayMetrics = context.resources.displayMetrics
            return displayMetrics.widthPixels
        }
    }


    class EvenItemDecoration(private val space: Int, private val column: Int) :
        RecyclerView.ItemDecoration() {
        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            val position = parent.getChildAdapterPosition(view)
            // 每个span分配的间隔大小
            val spanSpace = space * (column + 1) / column
            // 列索引
            val colIndex = position % column


            if (colIndex == 0 || colIndex == column - 1) {//保证两边没有边距
                outRect.left = 0
                outRect.right = 0
            } else {
                // 列左、右间隙
                outRect.left = space * (colIndex + 1) - spanSpace * colIndex
                outRect.right = spanSpace * (colIndex + 1) - space * (colIndex + 1)
            }
            // 行间距
            if (position >= column) {
                outRect.top = space
            }
            Log.e(
                "MainActivity",
                "${outRect.left} ${outRect.top}  ${outRect.right} ${outRect.bottom}"
            )
        }
    }
}
